package com.bootdo.hotel.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bootdo.common.utils.*;
import com.bootdo.haojiangboutils.MapBuild;
import com.bootdo.haojiangboutils.RequestParCheckUtils;
import com.bootdo.hotel.domain.*;
import com.bootdo.hotel.service.*;
import com.bootdo.lvyou.domain.LvyouScenicSpot;
import com.bootdo.lvyou.service.LvyouScenicSpotService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.bootdo.common.controller.BaseController;

/**
 * 
 * 
 * @author haojiangbo
 * @email 2100272728@qq.com
 * @date 2019-10-18 11:10:02
 */
 
@Controller
@RequestMapping("/hotel/hotelRoom")
public class HotelRoomController extends BaseController{


	@Autowired
	private HotelRoomTypeService hotelRoomTypeService;
	@Autowired
	private HotelRoomFloorService hotelRoomFloorService;
	@Autowired
	private HotelRoomService hotelRoomService;
	@Autowired
	private LvyouScenicSpotService lvyouScenicSpotService;
	@Autowired
	private HotelRoomDayStatusService hotelRoomDayStatusService;
	@Autowired
	private HotelOrderService hotelOrderService;

	@ModelAttribute
	public HotelRoom get(@RequestParam(required=false) Long id) {
		if (id != null){
			return hotelRoomService.get(id);
		}else{
			return new HotelRoom();
		}
	}


	
	//insert into sys_menu(parent_id,name,url,perms,type)  values (149,'测试','/hotel/hotelRoom','hotel:hotelRoom:hotelRoom',1)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (160,'修改','','hotel:hotelRoom:edit',2)
	//type 0是分类菜单 1是小菜但 2是按钮
	@GetMapping()
	@RequiresPermissions("hotel:hotelRoom:hotelRoom")	
	String HotelRoom(HotelRoom hotelRoom,HttpServletRequest request,HttpServletResponse response){
	    return "hotel/hotelRoom/hotelRoom";
	}
	
	@ResponseBody
	@PostMapping("/list")
	@RequiresPermissions("hotel:hotelRoom:hotelRoom")
	public PageUtils list(@RequestParam Map<String, Object> params,HttpServletRequest request) throws ParseException {

		String memberName = request.getParameter("memberName");
		String memberMobile = request.getParameter("memberMobile");
		String startTime = request.getParameter("startTime");
		List roomIdList = new ArrayList();
		MapBuild orderQuery = new MapBuild();
		List<Integer> status = new ArrayList<>();
		status.add(0);
		status.add(1);
		status.add(3);
		status.add(4);
		orderQuery.setKV("statusList", status);
		orderQuery.put("userId", getUserId());
		if(StringUtils.isNotEmpty(memberName)){
			orderQuery.put("memberName",memberName);
		}
		if(StringUtils.isNotEmpty(memberMobile)){
			orderQuery.put("memberMobile",memberMobile);
		}

		//去订单里面查询 不想些关联查询了
		if(orderQuery.size() > 2){
			if(StringUtils.isNotEmpty(startTime)){
				orderQuery.put("startTime",startTime);
			}
			 List<HotelOrder> hotelOrders = 	hotelOrderService.list(orderQuery);
			 if(hotelOrders.size() > 0){
				HotelOrder  hotelOrder = hotelOrders.get(0);
				if(StringUtils.isNotEmpty(hotelOrder.getRoomIdList())){
					String [] rm =  hotelOrder.getRoomIdList().split(",");
					for(String r: rm){
						roomIdList.add(r);
					}
				}else{
					if(null != hotelOrder.getRoomId()){
						roomIdList.add( hotelOrder.getRoomId());
					}
				}
			 }
		}

		//查询列表数据
        Query query = new Query(params);
		if(!isAdmin()){
			query.put("userId", getUserId());
		}
		if(roomIdList.size() > 0){
			query.put("roomIdList", roomIdList);
		}
		List<HotelRoom> hotelRoomList = hotelRoomService.list(query);
		int total = hotelRoomService.count(query);
		String now = DateUtils.format(new Date());
		if(StringUtils.isNotEmpty(request.getParameter("startTime"))){
			now = request.getParameter("startTime");
		}
		if(DateUtils.pasre(now,DateUtils.DATE_PATTERN).before(DateUtils.getCustomTime(0))){
			return 	 new PageUtils(new ArrayList<>(), 0);
		}
		String finalNow = now;
		hotelRoomList.forEach(item ->{
			HotelRoomDayStatus	hotelRoomDayStatus =  hotelRoomDayStatusService
					.getByRoomIdAndDay(item.getId(), finalNow);
			if(null != hotelRoomDayStatus){
				item.setStatus(hotelRoomDayStatus.getStatus());
			}else{
				item.setStatus(1);
			}
			switch (item.getStatus().intValue()){
				case 1:
					item.setStatusDep("空房");
					break;
				case 2:
					item.setStatusDep("脏房");
					break;
				case 3:
					item.setStatusDep("在住");
					break;
				case 4:
					item.setStatusDep("维修");
					break;
				case 5:
					item.setStatusDep("预订");
					break;
			}
		});
		PageUtils pageUtils = new PageUtils(hotelRoomList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("hotel:hotelRoom:edit")
	String add(HotelRoom hotelRoom,HttpServletRequest request,HttpServletResponse response){
	    return "hotel/hotelRoom/hotelRoomedit";
	}

	@PostMapping("/getById")
	@ResponseBody
	R getById(HotelRoom hotelRoom) {
		return R.ok().put("i",hotelRoom);
	}


	/**
	 * /hotel/hotelRoom/downloadByHotelId
	 * @param hotelId
	 * @param request
	 * @param response
	 */
	// 入口
	@RequestMapping("downloadByHotelId")
	public void downloadByHotelId(
			@RequestParam("hotelId")Long hotelId,
			HttpServletRequest request, HttpServletResponse response) {
		List<HotelRoom> list = hotelRoomService.list(MapBuild.getInstand().setKV("hotelId", hotelId));
		if (list != null && list.size() > 0) {
			ZipOutputStream zos = null;
			try {
				String downloadFilename = list.get(0).getHotelName();// 文件的名称
				downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 转换中文否则可能会产生乱码
				response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
				response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename + ".zip");// 设置在下载框默认显示的文件名
				zos = new ZipOutputStream(response.getOutputStream());
				int i = 1;
				for (HotelRoom room : list) {
					StringBuffer url = new StringBuffer("http://www.1900th.com/?roomId=");
					url.append(room.getId());
					if(StringUtils.isNotEmpty(room.getName())){
						zos.putNextEntry(new ZipEntry("序号："+i+"-房间号："+room.getName() + ".png"));// 命名
					}else{
						zos.putNextEntry(new ZipEntry("序号："+i + ".png"));// 命名
					}
					getBarCodeImgByUrl(url.toString(), zos);// 拼接了url
					i++;
				}
				zos.flush();
				zos.close();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (WriterException e) {
				e.printStackTrace();
			} finally {
				if (zos != null) {
					try {
						zos.flush();
						zos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	// 公共方法根据url生成二维码图片后写入输出流里
	public  static BufferedImage getBarCodeImgByUrl(String url ) throws  Exception{
		// 二维码参数
		int width = 200; // 图像宽度
		int height = 200; // 图像高度
		String format = "png";// 图像类型
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		hints.put(EncodeHintType.MARGIN, 0);
		BitMatrix bitMatrix;
		bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
		return MatrixToImageWriter.toBufferedImage(bitMatrix);
	}


	// 公共方法根据url生成二维码图片后写入输出流里
	public static void getBarCodeImgByUrl(String url, OutputStream os) throws WriterException, IOException {
		// 二维码参数
		int width = 200; // 图像宽度
		int height = 200; // 图像高度
		String format = "png";// 图像类型
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		hints.put(EncodeHintType.MARGIN, 0);
		BitMatrix bitMatrix;
		bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);




		MatrixToImageWriter.writeToStream(bitMatrix, format, os);
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("hotel:hotelRoom:edit")
	public R save( HotelRoom hotelRoom,HttpServletRequest request) throws ParseException {
		if(StringUtils.isNotEmpty(hotelRoom.getStartTime())){
			if(DateUtils.pasre(hotelRoom.getStartTime(),DateUtils.DATE_PATTERN).before(DateUtils.getCustomTime(0))){
				return R.error("开始时间不能小于当前时间");
			}
		}
		Object  r =  RequestParCheckUtils.checkPar(hotelRoom, new String[]{
				"floorId",
				"typeId",
				"hotelId",
	    });

		if(!r.equals(true)){
			return R.error(r.toString());
		}
		if(!isAdmin()){
			if(null == hotelRoom.getUserId()){
				hotelRoom.setUserId(getUserId());
				hotelRoom.setUserName(getUsername());
			}
		}

		if(StringUtils.isEmpty(hotelRoom.getFloorName())){
			HotelRoomFloor hotelRoomFloor  = hotelRoomFloorService.get(hotelRoom.getFloorId());
			if(null != hotelRoomFloor){
				hotelRoom.setFloorName(hotelRoomFloor.getName());
			}
		}


		if(StringUtils.isEmpty(hotelRoom.getTypeName())){
			HotelRoomType hotelRoomType  = hotelRoomTypeService.get(hotelRoom.getTypeId());
			if(null != hotelRoomType){
				hotelRoom.setTypeName(hotelRoomType.getName());
			}
		}
		if(StringUtils.isEmpty(hotelRoom.getHotelName())){
			LvyouScenicSpot lvyouScenicSpot  = lvyouScenicSpotService.get(hotelRoom.getHotelId());
			if(null != lvyouScenicSpot){
				hotelRoom.setHotelName(lvyouScenicSpot.getName());
			}
		}
		hotelRoom.setStatus(null);
		if(hotelRoomService.save(hotelRoom)>0){
			hotelRoom.setStatus(Integer.parseInt(request.getParameter("status")));
			String dateNow = DateUtils.format(new Date());



			if(StringUtils.isNotEmpty(hotelRoom.getStartTime())){
				dateNow = hotelRoom.getStartTime();
			}
			HotelRoomDayStatus hotelRoomDayStatus =  hotelRoomDayStatusService.getByRoomIdAndDay(hotelRoom.getId(),dateNow);
			if(null == hotelRoomDayStatus){
				hotelRoomDayStatus = new HotelRoomDayStatus();
				hotelRoomDayStatus.setHotelId(hotelRoom.getHotelId());
				hotelRoomDayStatus.setRoomId(hotelRoom.getId());
				hotelRoomDayStatus.setStatus(hotelRoom.getStatus());
				hotelRoomDayStatus.setRoomTypeId(hotelRoom.getTypeId());
				hotelRoomDayStatus.setDay(DateUtils.pasre(dateNow, DateUtils.DATE_PATTERN));
			}else{
				hotelRoomDayStatus.setHotelId(hotelRoom.getHotelId());
				hotelRoomDayStatus.setRoomId(hotelRoom.getId());
				hotelRoomDayStatus.setStatus(hotelRoom.getStatus());
				hotelRoomDayStatus.setRoomTypeId(hotelRoom.getTypeId());
			}
			hotelRoomDayStatusService.save(hotelRoomDayStatus);
			return R.ok();
		}
		return R.error();
	}



	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/update")
	@RequiresPermissions("hotel:hotelRoom:edit")
	public R update( HotelRoom hotelRoom,HttpServletRequest request) throws ParseException {
		hotelRoomService.save(hotelRoom);
		return R.ok();
	}

	
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("hotel:hotelRoom:edit")
	public R remove( Long id){
		if(hotelRoomService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("hotel:hotelRoom:edit")
	public R remove(@RequestParam("ids[]") Long[] ids){
		hotelRoomService.batchRemove(ids);
		return R.ok();
	}
	
}